package com.lotusfall.bank.web;

import com.lotusfall.bank.exception.MoneyNotEnoughException;
import com.lotusfall.bank.exception.TransferException;
import com.lotusfall.bank.service.AccountService;
import com.lotusfall.bank.service.impl.AccountServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//@WebServlet("/transfer")
public class AccountServlet extends HttpServlet {
    // 为了在这个对象的其他方法中也可以用，声明为实例变量
    private AccountService accountService = new AccountServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获取表单数据
        String fromActno = request.getParameter("fromActno");
        String toActno = request.getParameter("toActno");
        Double money = Double.parseDouble(request.getParameter("money"));

        try {
            // 调用Service的转账方法完成转账（表示层调业务层）
            accountService.transfer(fromActno,toActno,money);
            // 程序走到这儿表示转账一定成功了
            // 调用View完成展示结果
            response.sendRedirect(request.getContextPath() + "/success.html");
        } catch (MoneyNotEnoughException e) {
            response.sendRedirect(request.getContextPath() + "/error1.html");
        } catch (TransferException e) {
            response.sendRedirect(request.getContextPath() + "/error2.html");
        } catch (Exception e){
            response.sendRedirect(request.getContextPath() + "/error2.html");
        }
    }
}
